<template>
  <div class="ready">
    <section class="ready-info">
      <el-form :model="ruleForm"
               :rules="rules"
               ref="ruleForm"
               label-width="100px"
               class="yuyi-ruleForm">

        <el-upload
          class="yuyi-upload"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <el-form-item label="姓名" prop="username">
          <el-input v-model="ruleForm.username"
                    style="width: calc(100% - 200px)"></el-input>
        </el-form-item>
        <el-form-item label="证件类型">
          <el-select style="width: calc(100% - 200px)" v-model="ruleForm.certificateType" placeholder="请选择证件类型">
            <el-option v-for="(item, index) in certificateTypeDic"
                       :key="index"
                       :label="item.dictLabel"
                       :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="certificateNo">
          <el-input v-model="ruleForm.certificateNo" style="width: calc(100% - 200px)"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="userPhone">
          <el-input v-model="ruleForm.userPhone"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="ruleForm.gender">
            <el-radio v-for="(item, index) in genderDic"
                      :key="index"
                      :label="item.value">{{item.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系地址">
          <el-input type="textarea" :autosize="autosize" v-model="ruleForm.address"></el-input>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-radio-group v-model="ruleForm.userType">
            <el-radio v-for="(item, index) in userTypeDic"
                      :key="index"
                      :label="item.dictValue">{{item.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>

          <el-button type="primary"
                     size="small"
                     :loading="btnLoading"
                     @click="submitForm('ruleForm')">确定
          </el-button>
        </el-form-item>
      </el-form>
    </section>

    <section class="list-box">
      <div class="fun-btn">
        <el-button size="small" type="primary" @click="handleAddEmpty">新增</el-button>
        <search @onSubmit="onSearch">
          <el-form-item>
            <el-input placeholder="请输入内容"
                      v-model="searchData.val"
                      size="small"
                      clearable
                      class="input-with-select">
              <el-select style="width: 120px" clearable v-model="searchData.select" slot="prepend" placeholder="请选择">
                <el-option v-for="(item, index) in searchDic"
                           :key="index"
                           :label="item.dictLabel"
                           :value="item.dictValue"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </search>
      </div>
      <el-table
        :data="tableData.list"
        border
        v-loading="tableLoading"
        height="calc(100vh - 220px)"
        class="table">
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="60">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="username"
          label="姓名"
          width="180">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="certificateNo"
          label="证件号码"
          width="180">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="userPhone"
          label="联系方式">
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="130">
          <template slot-scope="scope">
            <el-button @click="handleDel(scope.row)" type="text" style="color: #F56C6C">删除</el-button>
            <el-button @click="handleEdit(scope.row)" type="text">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 40, 60, 80]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(tableData.total)">
      </el-pagination>
    </section>

  </div>
</template>

<script>

import {
  addDjOtherList,
  detDjOtherList,
  editDjOtherList,
  getDjOtherList
} from '../../../../api/utilize/utilizeDjOther'
import { cardid } from '../../../../util/validate'
import { getSysDicId } from '../../../../api/dictionary/dictionary'
import Search from '../../../../components/search/search'

export default {
  name: 'readyPeople',
  components: { Search },
  props: {
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        callback()
      } else {
        const reg = /^1[0-9]{10}$/
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    const idCard = (rule, value, callback) => {
      // 身份证号码验证
      const result = cardid(value)
      if (result.result) {
        callback()
      } else {
        return callback(new Error(result.msg))
      }
    }
    return {
      tableLoading: true,
      isShowReady: false,
      certificateTypeDic: [], // 身份类型字典
      userTypeDic: [], // 用户类型
      searchDic: [{
        dictLabel: '用户姓名',
        dictValue: 'username'
      }, {
        dictLabel: '证件号码',
        dictValue: 'certificateNo'
      }], // 搜索
      genderDic: [{
        label: '女',
        value: 0
      }, {
        label: '男',
        value: 1
      }, {
        label: '其他',
        value: 2
      }],
      autosize: {
        minRows: 2,
        maxRows: 2
      },
      imageUrl: '',
      ruleForm: {
        username: '', // 用户姓名
        certificateType: '', // 证件类型
        certificateNo: '', // 证件号码
        userPhone: '', // 用户电话
        gender: '', // 性别
        address: '', // 联系地址
        userType: '' // 用户类型
      },
      rules: {
        username: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        certificateNo: [
          {
            required: true,
            validator: idCard,
            trigger: 'blur'
          }
        ],
        userPhone: [
          {
            validator: checkPhone,
            trigger: 'blur'
          }
        ]
      },
      btnLoading: false,
      page: {
        pageNo: 1,
        pageSize: 1000
      },
      searchData: {
        val: '',
        select: 'username'
      },
      params: [],
      tableData: {}
    }
  },
  mounted () {
    this.getList()
    this.getDic()
  },
  watch: {
    rowData () {
      this.getList()
      this.handleAddEmpty()
    }
  },
  methods: {
    getDic () {
      getSysDicId('document_type').then(res => {
        // 获取证件类型
        this.certificateTypeDic = res.data.data
        this.ruleForm.certificateType = this.certificateTypeDic[0].dictValue
      })
      getSysDicId('user_type').then(res => {
        // 用户类型
        this.userTypeDic = res.data.data
        this.ruleForm.userType = this.userTypeDic[0].dictValue
      })
    },
    getList () {
      this.tableLoading = true
      const param = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        params: [{
          name: 'idUseRegister',
          op: 'eq',
          value: this.rowData.id
        }]
      }
      if (this.params.length > 0) {
        param.params = param.params.concat(this.params)
      }
      getDjOtherList(param).then(res => {
        this.tableData = res.data.data
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.page.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.page.pageNo = val
      this.getList()
    },
    onSearch () {
      // 搜索
      this.page.pageNo = 1
      this.params = []
      if (this.searchData.val) {
        this.params.push({
          name: this.searchData.select,
          op: 'like',
          value: this.searchData.val
        })
      }
      this.getList()
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      /* const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M */
    },
    handleAddEmpty () {
      // 新增时清空表单
      this.isShowReady = false
      this.ruleForm.username = '' // 用户姓名
      this.ruleForm.certificateNo = '' // 证件号码
      this.ruleForm.userPhone = '' // 用户电话
      this.ruleForm.gender = '' // 性别
      this.ruleForm.address = '' // 联系地址
    },
    handleEdit (row) {
      // 编辑
      this.isShowReady = true
      Object.keys(row).forEach(key => {
        this.ruleForm[key] = row[key]
      })
    },
    submitForm (formName, type) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.btnLoading = true
          if (this.isShowReady) {
            // 编辑修改
            editDjOtherList(this.ruleForm).then(() => {
              this.$message.success('修改成功！')
              this.btnLoading = false
              this.isShowReady = false
              this.handleAddEmpty()
              this.getList()
            }).catch(() => {
              this.btnLoading = false
            })
          } else {
            // 新增
            delete this.ruleForm.id
            this.ruleForm.idUseRegister = this.rowData.id
            addDjOtherList(this.ruleForm).then(() => {
              this.$message.success('新增成功！')
              this.btnLoading = false
              this.handleAddEmpty()
              this.getList()
            }).catch(() => {
              this.btnLoading = false
            })
          }
        } else {
          return false
        }
      })
    },
    handleDel (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        detDjOtherList([row.id]).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "../../../../styles/mixin";

  .ready {
    padding: 10px 20px;
    background: #e7e7e7;
    height: 100%;
    overflow-y: auto;
    @include fj;

    .ready-info {
      margin-bottom: 20px;
      background: #fff;
      width: 585px;

      .yuyi-ruleForm {
        padding: 30px 30px 10px 0;
        position: relative;

        .yuyi-upload {
          position: absolute;
          right: 30px;
          z-index: 2;
          border: 1px dashed #ccc;

          .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;

            &:hover {
              border-color: #409EFF;
            }
          }

          .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 160px;
            height: 160px;
            line-height: 160px;
            text-align: center;
          }

          .avatar {
            width: 178px;
            height: 178px;
            display: block;
          }
        }
      }
    }

    .list-box {
      background: #fff;
      padding-bottom: 70px;
      width: calc(100% - 590px);
    }
    .fun-btn{
      @include fj;
      align-items: flex-start;
      padding: 15px 0px 0 10px;
    }
  }
</style>
